package pers.vic.practice.base.web;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;
import pers.vic.boot.base.tool.Tools;
import pers.vic.practice.base.constant.BaseConstant;
import pers.vic.practice.base.enums.PermissionType;
import pers.vic.practice.base.enums.UserType;
import pers.vic.practice.base.model.Principal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Stream;

/**
 * 描述: 权限拦截
 * @author Vic.xu
 * @date 2022-04-11 16:16
 */
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        PermissionType permissionType = method.getMethodAnnotation(PermissionType.class);
        //默认需要登录
        boolean needLogin = true;
        if (permissionType != null) {
            needLogin = permissionType.needLogin();
        }
        //不需要登录 则不拦截
        if (!needLogin) {
            return super.preHandle(request, response, handler);
        }

        Principal principal = (Principal) WebUtils.getSessionAttribute(request, BaseConstant.USER_SESSION_KEY);
        if (principal == null) {
            //拦截 前往登录页面
            toPage(request, response, BaseConstant.LOGIN_PAGE);
            return false;
        }
        //暂时不在判断url 直接判断权限类类型
        //权限类型判断 默认是通过的
        boolean typeCheck = true;
        if (permissionType != null) {
            UserType userType = principal.getUserType();
            typeCheck = Stream.of(permissionType.permissions()).anyMatch(type -> type == userType);
        }
        if (!typeCheck) {
            //拦截 前往登录页面
            toPage(request, response, BaseConstant.LOGIN_PAGE);
            return false;
        }
        return super.preHandle(request, response, handler);
    }


    //当前访问的url
        /*String currentUrl = Tools.getRequestUrl(request);
        List<String> urls = principal.getUrls();
        if (urls != null && urls.contains(currentUrl)) {
            toPage(request, response, BaseConstant.LOGIN_PAGE);
            return false;
        }*/

    /**
     * 前往某个页面
     */
    private void toPage(HttpServletRequest request, HttpServletResponse response, String page) throws ServletException, IOException {
        //request.getRequestDispatcher(page).forward(request, response);
        response.sendRedirect(page);
    }
}
